﻿using UnityEngine;
using UnityEditor;

namespace CWM.Skinn
{
    public class SkinnShapeLoaderWizard : ScriptableWizard
    {
        public static SkinnShapeLoaderWizard wizard = null;
        public static SkinnedMeshRenderer renderer = null;
        public static Vector2 scroll = Vector2.zero;

        public bool clearOldShapes = false;
        public bool normals = true;
        public bool tangents = true;

        [Tooltip("all child renderers that have a matching vertex count will be loaded as a blend-shape.")]
        public GameObject[] shapeRenderers = new GameObject[0];

        public readonly string help = "You can drag multiple items into the header of an array.";

        public static void ShowWizard(SkinnedMeshRenderer renderer)
        {
            SkinnShapeLoaderWizard.renderer = renderer;
            wizard = DisplayWizard<SkinnShapeLoaderWizard>(SkinnEx.EnforceObjectName(renderer) + "");
        }

        private void OnEnable() { if (wizard & wizard != this) wizard.Close(); wizard = this; scroll = Vector2.zero; }
        private void OnWizardUpdate() { if (!renderer) { this.Close(); return; } helpString = help; }

        private void OnWizardCreate()
        {
            if (!renderer.GetSharedMesh()) return;
            var mesh = renderer.GetSharedMesh().Clone() as Mesh;

            if (clearOldShapes) mesh.ClearBlendShapes();

            foreach (var go in shapeRenderers)
            {
                if (!go) continue;

                var renderers = go.GetComponentsInChildren<Renderer>();

                for (int i = 0; i < renderers.Length; i++)
                {
                    var renderer = renderers[i];
                    var shapeName = renderers.Length == 1 ? go.name : renderer.transform.name;
                    mesh.AddBlendshape(renderer.GetSharedMesh(), shapeName, normals, tangents);
                }
            }

            Undo.RecordObject(renderer, "Load Blendshapes");

            renderer.SetSharedMesh(mesh);
        }

        public void Create()
        {
            OnWizardCreate();
        }
    }
}